package com.tianlang.security.tool;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.tianlang.cache.AuthorityCache;
import com.tianlang.domain.pojo.Authority;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 自定义标签
 * 
 * @author Administrator
 *
 */
public class AuthorityTag implements TemplateDirectiveModel {
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		String value = params.get("value").toString();
		Map<String, List<Authority>> map = AuthorityCache.Authority_Map;
		SecurityContext context = SecurityContextHolder.getContext();
		Authentication auth = (Authentication) context.getAuthentication();
		List<Authority> list = map.get(value);
		if (list != null && auth != null) {
			for (GrantedAuthority ga : auth.getAuthorities()) {
				for (Authority security : list) {
					if (security.getRoleName().equalsIgnoreCase(ga.getAuthority())) {
						body.render(env.getOut());
					}
				}
			}
		}
	}

}
